#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <dirent.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <cstdlib>

// 函数声明
void getProcesses(std::vector<int>& pids);
std::string getExecutablePath(int pid);

int main() {
    std::vector<int> pids;
    getProcesses(pids);

    for (std::vector<int>::iterator it = pids.begin(); it != pids.end(); ++it) {
        std::string path = getExecutablePath(*it);
        if (!path.empty()) {
            std::cout << "PID: " << *it << ", Path: " << path << std::endl;
        }
    }

    return 0;
}

// 获取所有运行的进程ID
void getProcesses(std::vector<int>& pids) {
    DIR* dir = opendir("/proc");
    if (dir == NULL) {
        perror("opendir(/proc)");
        return;
    }

    struct dirent* entry;
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            int pid = atoi(entry->d_name);
            if (pid > 0) {
				getExecutablePath(pid);
              //  pids.push_back(pid);
            }
        }
    }
    closedir(dir);
}

// 获取指定进程的可执行文件路径
std::string getExecutablePath(int pid) {
    std::stringstream ss;
    ss << "/proc/" << pid << "/exe";
    char path[PATH_MAX];
    ssize_t len = readlink(ss.str().c_str(), path, sizeof(path) - 1);
    if (len != -1) {
        path[len] = '\0';
		std::cout << "PID: " << pid << ", Path: " << std::string(path) << std::endl;
        return std::string(path);
    }
    return "";
}
